
package com.hd.sup.modules.vehicle.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Maps;
import com.hd.common.constant.BizConstant;
import com.hd.common.page.BaseController;
import com.hd.common.reqres.request.RequestData;
import com.hd.common.reqres.response.Result;
import com.hd.common.utils.GenUtil;
import com.hd.common.utils.UserUtils;
import com.hd.common.utils.ValueUtils;
import com.hd.sup.modules.vehicle.model.Vehicle;
import com.hd.sup.modules.vehicle.model.VehicleAlarmDailyStatis;
import com.hd.sup.modules.vehicle.model.VehicleDailyStatis;
import com.hd.sup.modules.vehicle.model.VehicleEndPos;
import com.hd.sup.modules.vehicle.service.IVehicleAlarmDailyStatisService;
import com.hd.sup.modules.vehicle.service.IVehicleDailyStatisService;
import com.hd.sup.modules.vehicle.service.IVehicleEndPosService;
import com.hd.sup.modules.vehicle.service.IVehicleService;
import com.hd.sup.modules.vehicle.wrapper.VehicleTrailWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author chentl
 * @version V1.0
 * @Project 交通运输第三方监测平台
 * @Title VehicleController.java
 * @Description 车辆控制器
 * @Package com.hd.sup.modules.vehicle.controller
 * @date 2020/12/28 5:05 下午
 * @Copyright: 深圳市宏电技术股份有限公司 All rights reserved.
 */
@Slf4j
@RestController
@RequestMapping("/vehicle")
public class VehicleController extends BaseController {

    public static final String PROVINCE = "province";
    public static final String CITY = "city";
    public static final String REGION = "region";
    public static final int ZERO = 0;

    @Resource
    private UserUtils userUtils;

    @Resource
    private IVehicleAlarmDailyStatisService vehicleAlarmDailyStatisService;

    @Resource
    private IVehicleDailyStatisService vehicleDailyStatisService;

    @Resource
    private IVehicleService vehicleService;

    @Resource
    private IVehicleEndPosService vehicleEndPosService;

    /**
     * @return com.hd.sup.core.reqres.response.Result<?>
     * @author chentl
     * @description 查询所有市的车辆总数聚合数据
     * @date 2021/1/4 10:12 上午
     * @params []
     */
    @GetMapping("/vehicleMap")
    public Result<?> vehicleMap(String vision, String regionCode) {
        //枚举: province city region
        if (StringUtils.isBlank(vision)) return Result.error("参数中 vision 为空");

        Map<String, Object> resultMap = Maps.newHashMap();

        if (PROVINCE.equals(vision)) {
            List<Map<String, Object>> aggregation_vehicle = vehicleService.getAllVehicleMap("", 3, 4);
            resultMap.put("aggregation_vehicle", aggregation_vehicle);

        } else if (CITY.equals(vision)) {
            VehicleEndPos param = new VehicleEndPos(regionCode, 4);
            List<Map<String, Object>> aggregation_vehicle = vehicleService.getAllVehicleMap(regionCode, 5, 6);
            List<Map<String, Object>> gps_points = (List<Map<String, Object>>) new VehicleTrailWrapper(vehicleEndPosService.getVehicleGps(param)).warp();
            resultMap.put("aggregation_vehicle", aggregation_vehicle);
            resultMap.put("gps_points", gps_points);

        } else if (REGION.equals(vision)) {
            VehicleEndPos param = new VehicleEndPos(regionCode, 6);
            List<Map<String, Object>> gps_points = (List<Map<String, Object>>) new VehicleTrailWrapper(vehicleEndPosService.getVehicleGps(param)).warp();
            resultMap.put("gps_points", gps_points);
        }


        return Result.success(resultMap);
    }

    /**
     * @return com.hd.sup.core.reqres.response.Result<?>
     * @author chentl
     * @description 分类车辆统计
     * @date 2020/12/28 11:23 上午
     * @params [world]
     */
    @PostMapping("/vehicleTypeStatis")
    public Result<?> vehicleTypeStatis(@RequestBody RequestData requestData) {

        String startDateStr = requestData.getString("startDateStr");
        String endDateStr = requestData.getString("endDateStr");
        String currentDate = requestData.getString("currentDate");
        if (StringUtils.isNotBlank(currentDate) && (StringUtils.isNotBlank(startDateStr) || StringUtils.isNotBlank(endDateStr)))
            return Result.error("参数currentDate 和 起始时间 不允许同时选择");

        List<String> deptIds = userUtils.getDeptIdList();
        VehicleDailyStatis param = new VehicleDailyStatis(startDateStr, endDateStr, currentDate);
        List<VehicleDailyStatis> list = vehicleDailyStatisService.getDailyVehicleNumData(param, deptIds);

        Map<String, Object> resultMap = Maps.newHashMap();
        // 封装数据
        if (CollectionUtils.isNotEmpty(list))
            vehicleDailyStatisService.fillVehicleByTransType(resultMap, list, deptIds);
        else vehicleDailyStatisService.fillVehicleByTransTypeForEmpty(resultMap, deptIds);

        return Result.success(resultMap);
    }

    /**
     * @return com.hd.sup.core.reqres.response.Result<?>
     * @author chentl
     * @description 车辆总数统计
     * @date 2020/12/28 3:58 下午
     * @params []
     */
    @PostMapping("/vehicleSumStatis")
    public Result<?> vehicleSumStatis(@RequestBody RequestData requestData) {

        String currentDate = requestData.getString("currentDate");
        if (StringUtils.isBlank(currentDate)) return Result.error("参数 currentDate 为空");

        List<String> deptIds = userUtils.getDeptIdList();
        Map<String, Object> resultMap = Maps.newHashMap();
        // 封装数据
        VehicleDailyStatis sumData = vehicleDailyStatisService.getDailyVehicleSumData(currentDate, deptIds);
        Integer vehicleSum = vehicleService.countVehicleNum(null, null, deptIds);
        resultMap.put("vehicle_sum", vehicleSum);

        Integer alarmVehicleNum = Objects.isNull(sumData) ? ZERO : ValueUtils.parseInteger(sumData.getAlarmVehicleNum());
        Integer onlineSum = Objects.isNull(sumData) ? ZERO : ValueUtils.parseInteger(sumData.getOnlineSum());
        Integer goOnlineSum = Objects.isNull(sumData) ? ZERO : ValueUtils.parseInteger(sumData.getGoOnlineSum());

        resultMap.put("alarm_vehicle_num", alarmVehicleNum);
        resultMap.put("online_sum", onlineSum);
        resultMap.put("go_online_sum", goOnlineSum);
        //计算百分比
        resultMap.put("alarm_rate", ValueUtils.getRate(alarmVehicleNum, vehicleSum, 2));
        resultMap.put("online_rate", ValueUtils.getRate(onlineSum, vehicleSum, 2));
        resultMap.put("go_online_rate", ValueUtils.getRate(goOnlineSum, vehicleSum, 2));
        return Result.success(resultMap);
    }

    /**
     * @return com.hd.sup.core.reqres.response.Result<?>
     * @author chentl
     * @description 车辆上线趋势
     * @date 2020/12/30 9:00 上午
     * @params [requestData]
     */
    @PostMapping("/vehicleGoOnlineTrend")
    public Result<?> getVehicleGoOnlineTrend(@RequestBody RequestData requestData) {
        String dateRange = requestData.getString("dateRange");
        String startDateStr = requestData.getString("startDateStr");
        String endDateStr = requestData.getString("endDateStr");

        if (StringUtils.isNotBlank(dateRange) && (StringUtils.isNotBlank(startDateStr) || StringUtils.isNotBlank(endDateStr)))
            return Result.error("参数范围时间和起始时间不允许同时选择");

        Map<String, Object> resultMap = Maps.newHashMap();
        List<String> deptIds = userUtils.getDeptIdList();

        //填充车辆上线趋势数据
        for (BizConstant.VehicleTransType one : BizConstant.VehicleTransType.values()) {
            List<Map<String, Object>> data = vehicleDailyStatisService.getGoOnlineTrendData(dateRange, startDateStr, endDateStr, one.key(), deptIds);
            resultMap.put(one.property(), data);
        }

        return Result.success(resultMap);
    }

    /**
     * @return com.hd.sup.core.reqres.response.Result<?>
     * @author chentl
     * @description 查询车辆报警趋势
     * @date 2021/2/2 10:57 上午
     * @params [requestData]
     */
    @PostMapping("/getVehicleAlarmTrend")
    public Result<?> getVehicleAlarmTrend(@RequestBody RequestData requestData) {
        String startDateStr = requestData.getString("startDateStr");
        String endDateStr = requestData.getString("endDateStr");
        String dateRange = requestData.getString("dateRange");
        String platNo = requestData.getString("platNo");
        String platNoColor = requestData.getString("platNoColor");

        if (StringUtils.isNotBlank(dateRange) && (StringUtils.isNotBlank(startDateStr) || StringUtils.isNotBlank(endDateStr)))
            return Result.error("参数范围时间和起始时间不允许同时选择");
        if (StringUtils.isBlank(platNo)) return Result.error("参数 platNo 为空");
        if (StringUtils.isBlank(platNoColor)) return Result.error("参数 platNoColor 为空");

        Map<String, Object> resultMap = Maps.newHashMap();
        List<String> deptIds = userUtils.getDeptIdList();

        //填充车辆报警趋势数据
        for (BizConstant.AlarmType one : BizConstant.AlarmType.values()) {
            VehicleAlarmDailyStatis param = new VehicleAlarmDailyStatis(platNo, platNoColor, startDateStr, endDateStr, dateRange);
            List<Map<String, Object>> data = vehicleAlarmDailyStatisService.getVehicleAlarmTrendData(param, one.key(), deptIds);
            resultMap.put(one.property(), data);
        }

        return Result.success(resultMap);
    }

    /**
     * @return com.hd.sup.core.reqres.response.Result<?>
     * @author chentl
     * @description 报警企业排名TOP 5
     * @date 2020/12/29 3:12 下午
     * @params [requestData]
     */
    @GetMapping("/vehicleAlarmTop5")
    public Result<?> vehicleAlarmTop5() {
        List<String> deptIds = userUtils.getDeptIdList();

        List<Map<String, Object>> result = vehicleDailyStatisService.getVehicleTop5(deptIds);
        return Result.success(result);
    }

    /**
     * @return com.hd.sup.core.reqres.response.Result<?>
     * @author chentl
     * @description 车辆维度报警信息列表
     * @date 2020/12/30 4:21 下午
     * @params []
     */
    @PostMapping("/vehicleAlarm")
    public Result<?> vehicleAlarm(@RequestBody RequestData requestData) {

        Long current = requestData.getCurrent();
        Long size = requestData.getSize();
        String startDateStr = requestData.getString("startDateStr");
        String endDateStr = requestData.getString("endDateStr");
        String regionCode = requestData.getString("regionCode");
        String enterpriseNo = requestData.getString("enterpriseNo");
        String platNo = requestData.getString("platNo");
        String enterpriseName = requestData.getString("enterpriseName");
        String dateRange = requestData.getString("dateRange");

        String sort = requestData.getString("sort");
        String order = requestData.getString("order");
        //入参校验
        if (StringUtils.isNotBlank(dateRange) && (StringUtils.isNotBlank(startDateStr) || StringUtils.isNotBlank(endDateStr)))
            return Result.error("参数范围时间和起始时间不允许同时选择");
        if (current == null || size == null) return Result.error("参数 current 或 size 不允许为空");

        VehicleAlarmDailyStatis param = new VehicleAlarmDailyStatis(platNo, enterpriseNo, enterpriseName, regionCode, startDateStr, endDateStr, dateRange, sort, order);

        Page<Map<String, Object>> page = new Page<>();
        page.setCurrent(current);
        page.setSize(size);
        List<Map<String, Object>> result = vehicleAlarmDailyStatisService.getAlarmVehiclePage(page, param);
        page.setRecords(result);

        return Result.success(page);
    }

    @PostMapping("/list")
    public Result<?> list(@RequestBody RequestData requestData) {
        Long current = requestData.getCurrent();
        Long size = requestData.getSize();
        String platNo = requestData.getString("platNo");
        String vehicleType = requestData.getString("vehicleType");
        String transType = requestData.getString("transType");
        String regionCode = requestData.getString("regionCode");
        //入参校验
        if (current == null || size == null) return Result.error("参数 current 或 size 不允许为空");

        Vehicle param = new Vehicle(platNo, vehicleType, transType, regionCode);

        Page<Map<String, Object>> page = new Page<>();
        page.setCurrent(current);
        page.setSize(size);
        List<Map<String, Object>> result = vehicleService.pageList(page, param);
        page.setRecords(result);
        return Result.success(page);
    }

    /**
     * @return com.hd.sup.core.reqres.response.Result<?>
     * @author chentl
     * @description 删除车辆信息
     * @date 2020/12/31 4:18 下午
     * @params [ids]
     */
    @DeleteMapping("/delete/{ids}")
    public Result<?> delete(@PathVariable() String ids) {
        if (StringUtils.isBlank(ids)) return Result.error("参数 ids 为空");
        vehicleService.deleteByIds(Arrays.asList(ids.split(BizConstant.Common.SEPARATOR.key())));
        return Result.success();
    }

    /**
     * @return com.hd.sup.core.reqres.response.Result<?>
     * @author chentl
     * @description 保存或更新
     * @date 2020/12/31 4:19 下午
     * @params [enterprise]
     */
    @PostMapping("/saveOrUpdate")
    public Result<?> saveOrUpdate(Vehicle vehicle) {
        //入参校验
        if (vehicle == null) return Result.error("参数为空");

        if (StringUtils.isBlank(vehicle.getId())) {
            vehicle.setId(GenUtil.newId());
            vehicle.setCreateBy(getCurrentUser().getUsername());
        }
        vehicle.setUpdateBy(getCurrentUser().getUsername());
        vehicle.insertOrUpdate();
        return Result.success(vehicle);
    }


}
